package com.zzw.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.zzw.util.QuestionDao;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class IndexActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);

        Thread t = new Thread(){
            @Override
            public void run() {
                try {
                    SharedPreferences s = getSharedPreferences("question_flag", MODE_PRIVATE);
                    boolean savedFlag = s.getBoolean("flag", false);
                    if(savedFlag){
                        sleep(3000);
                    }else {
                        QuestionDao.deleteAllData();
                        InputStream is = getAssets().open("question.txt");
                        // 保存读取的数据以便后面的利用
                        loadInputStream(is);
                        SharedPreferences.Editor e = s.edit();
                        e.putBoolean("flag",true);
                        e.commit();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(IndexActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
            }
        };
        t.start();
    }

    public void loadInputStream(InputStream inputStream)throws IOException{
        BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
        String line;
        StringBuffer question = new StringBuffer();
        StringBuffer answer = new StringBuffer();
        boolean questionFlag = false;
        while((line = buffer.readLine())!=null){
            if(line.equals("Start_Question_Flag")){   // 问题开始
                questionFlag = true;
            }else if (line.equals("Start_answer_Flag")) {  // 答案开始
                questionFlag = false;
            }else if (line.equals("End_Flag")) {     // 读取结束
                Map<String,Object> map = new HashMap<>();
                map.put("question",question);
                map.put("answer", answer);
                QuestionDao.insertData(map);   // 数据插入数据库

                // 清空问题和答案的变量
                question = new StringBuffer();
                answer = new StringBuffer();
            }else{
                if (questionFlag) {
                    question.append(line); // 读取问题
                }else{
                    answer.append(line);   // 读取答案
                }
            }
        }
    }
}
